<script lang="ts">
import { ref, defineProps } from "vue";
import axios from "axios";

import { DwtUIOperations } from "./tools/dwtUIOperations";
import { getEl, getInputEl } from "./tools/common";
import { useGlobalStore } from "@/stores/modules/global";
import { useDictionryStore } from "@/stores/modules/dictionary";
import mittBus from "@/utils/mittBus";

let strFileNameWithoutExt = ref("FN-2025-Y-1");
let strExtension = ref("pdf");
let strAllPages = ref("true");

const { setFileDirName, setFileName, setExtensionValue } = useDictionryStore();

const fileTypeOpts = [
  {
    label: "pdf",
    value: "pdf"
  },
  {
    label: "tif",
    value: "tif"
  },
  {
    label: "jpg",
    value: "jpg"
  },
  {
    label: "png",
    value: "png"
  }
  // {
  //   label: "bmp",
  //   value: "bmp"
  // }
];

const globalStore = useGlobalStore();

export default {
  props: {
    dwtUtil: {
      required: true,
      type: DwtUIOperations
    },
    showUpload: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      strFileNameWithoutExt,
      strExtension,
      strAllPages,
      fileTypeOpts,
      globalStore,
      fileDir: "",
      fileIndex: 0, // 文件索引
      fileDirIndex: 0, // 文件夹索引
      pageCount: 10 // 默认页数
    };
  },

  mounted() {
    this.handleChangeDic("");
    this.handleRefreshFileName("");
    mittBus.on("dialogSelectedNodes", (node: any) => {
      console.log("***** 当前选中节点 *****", node);
      if (node.isDirectory) {
        this.fileDir = node.name;
        this.handleChangeDic("selectedNodes"); // dialog中的树节点点击
      }
    });
  },

  methods: {
    // 取文件名的纯数字
    extractNumberFromFilename(filename: string) {
      // 使用正则表达式匹配最后一个下划线后的数字部分
      const regex = /_(\d+)(?=\.[^.]+$)/;
      const match = filename.match(regex);

      // 如果匹配成功，返回数字部分；否则返回 null 或其他默认值
      return match ? match[1] : "";
    },
    handleChangeDic(type: string) {
      if (!type) {
        this.fileDir = `FN-2025-Y-${this.fileDirIndex + 1}`;
        this.fileDirIndex += 1; // 文件夹索引加1
      }
      setFileDirName(this.fileDir);
      this.handleRefreshFileName("dicFresh");
      mittBus.emit("fileUploadEnd");
      if (!this.showUpload) {
        // 非上传面板才请求
        axios({
          url: `/api/api/MasterFile/folders?path=${this.fileDir}`,
          method: "post"
        })
          .then(res => {
            (this.$parent as any).refreshEditBarNodes(); // 刷新dialog文件树
          })
          .catch(err => {
            console.log("err", err);
          });
      }
    },
    handleRefreshFileName(type: string) {
      if (!this.showUpload) {
        if (type !== "dicFresh") {
          this.fileIndex += 1;
        }
        if (this.fileIndex > 1 && type == "dicFresh") {
          this.fileIndex = 1;
        }
        strFileNameWithoutExt.value = `${this.fileDir}-${this.fileIndex}`;
      } else {
        strFileNameWithoutExt.value = `FN-2025-Y-${this.fileIndex + 1}`;
      }
      setFileName(strFileNameWithoutExt.value);
    },
    handleFileNameChange(val: string) {
      // let el = evt.target as HTMLInputElement;
      strFileNameWithoutExt.value = val;
      setFileName(strFileNameWithoutExt.value);
    },

    handleSaveConfigChange(val: string) {
      // let el = evt.target as HTMLSelectElement;
      // let strNewExtension = el.value;
      setExtensionValue(val); // 设置文件扩展名
      if (val == "jpg" || val == "png" || val == "tif") {
        // 这些格式默认为单页
        strAllPages.value = "false";
      }
      strExtension.value = val;
      this.onchangeImageExtension(strExtension.value);
    },

    onchangeImageExtension(strExtension: string) {
      let currentPage = getInputEl("CurrentPage");
      let allPages = getInputEl("AllPages");

      // set AllPages OR CurrentPage
      switch (strExtension) {
        case "pdf":
          strAllPages.value = "true";
          break;
        case "tif":
        case "bmp":
        case "jpg":
        case "png":
          strAllPages.value = "false";
          break;
        default:
          break;
      }

      // set Enabled
      if (strExtension == "pdf" || strExtension == "tif") {
        if (currentPage) {
          currentPage.disabled = false;
        }

        if (allPages) {
          allPages.disabled = false;
        }
      } else {
        if (currentPage) {
          currentPage.disabled = true;
        }

        if (allPages) {
          allPages.disabled = true;
        }
      }
    },

    saveOrUploadImage(saveType: any) {
      console.log("saveOrUploadImage", saveType);
      setFileName(strFileNameWithoutExt.value); // 将文件名称存储到pinia中
      this.dwtUtil.save(saveType, strFileNameWithoutExt.value, strExtension.value, strAllPages.value, this.pageCount);
    },

    showCustomInfo() {
      let el = getEl("customDetail");
      if (el) el.style.display = "";
    },

    hideCustomInfo() {
      let el = getEl("customDetail");
      if (el) el.style.display = "none";
    },

    onclickShowUploadedFiles() {
      this.dwtUtil.onclickShowUploadedFiles();
    },

    onclickSaveDocuments() {
      this.dwtUtil.onclickSaveDocuments();
    }
  }
  // onBeforeRouteUpdate((to, from, next) => {
  //   // to and from are both route objects. must call `next`.
  // })
};
</script>
<template>
  <div>
    <div id="divUpload" class="divinput mt30" style="position: relative">
      <ul>
        <li>
          <div class="divType" :style="`background-color: ${globalStore.primary}`">
            {{ showUpload ? "保存文件" : "文件配置" }}
          </div>
        </li>
      </ul>
    </div>
    <div id="tabCon" :style="`height: ${showUpload ? '203px' : '140px'}`" class="divinput mt30">
      <div id="divSaveDetail">
        <ul>
          <li v-if="!showUpload" class="fileDir">
            <p>文件目录:</p>
            <div class="file-dic-line">
              <el-input
                style="width: 368px"
                v-model="fileDir"
                size="small"
                placeholder="文件目录名称"
                @blur="handleChangeDic('blur')"
              />
              <el-tooltip class="box-item" effect="dark" content="更新目录名称" placement="top-start">
                <el-icon @click="handleChangeDic('')"><Refresh /></el-icon>
              </el-tooltip>
            </div>
          </li>
          <li>
            <p>文件名称:</p>
            <div class="file-name" :style="`align-items: ${showUpload ? 'flex-end' : 'center'}`">
              <!-- <input
                type="text"
                size="20"
                id="txt_fileName"
                v-model="strFileNameWithoutExt"
                v-on:change="handleFileNameChange($event)"
              /> -->
              <div class="name-content">
                <el-input
                  :style="`width: ${showUpload ? '252px' : '226px'}`"
                  v-model="strFileNameWithoutExt"
                  placeholder="Please input"
                  @change="handleFileNameChange"
                />
                <span> . </span>
                <!-- <select
                  size="1"
                  id="fileType"
                  style="position: relative; width: 25%"
                  v-model="strExtension"
                  v-on:change="handleSaveConfigChange($event)"
                >
                  <option value="pdf">pdf</option>
                  <option value="tif">tif</option>
                  <option value="jpg">jpg</option>
                  <option value="png">png</option>
                  <option value="bmp">bmp</option>
                </select> -->
                <el-select style="width: 103px" v-model="strExtension" @change="handleSaveConfigChange">
                  <el-option v-for="item in fileTypeOpts" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
              <el-tooltip v-if="!showUpload" class="box-item" effect="dark" content="更新文件名称" placement="top-start">
                <el-icon @click="handleRefreshFileName"><Document /></el-icon>
              </el-tooltip>
            </div>
          </li>
          <li v-if="showUpload" class="page-range">
            <span> 页面范围: </span>
            <!-- <label for="CurrentPage" style="margin-left: 5px"
              ><input type="radio" id="CurrentPage" name="Pages" v-model="strAllPages" value="false" />当前页&nbsp;</label
            >
            <label for="AllPages"
              ><input type="radio" id="AllPages" name="Pages" v-model="strAllPages" value="true" />所有页面</label
            > -->
            <el-radio-group v-model="strAllPages">
              <el-radio label="false">单页&nbsp;</el-radio>
              <el-radio v-if="strExtension == 'pdf'" label="1">多页&nbsp;</el-radio>
              <el-radio v-if="strExtension == 'pdf'" label="true">{{
                strExtension == "pdf" ? "所有页面合成" : "所有页面"
              }}</el-radio>
              <el-input v-if="strAllPages === '1'" type="number" v-model="pageCount" />
            </el-radio-group>
          </li>
          <li v-if="showUpload">
            <span class="customInfo" @mouseover="showCustomInfo()" @mouseout="hideCustomInfo()"
              >自定义元数据 <i class="fa fa-download"></i
            ></span>
            :
            <div style="display: none" id="customDetail">可添加随图上传的扩展信息</div>
            <input type="text" id="txt_CustomInfo" />
          </li>
          <li class="save-btns">
            <!-- <input id="btnUpload" class="btnOrg" type="button" value="上传" v-on:click="saveOrUploadImage('server')" /> -->
            <el-button v-if="showUpload" type="primary" @click="saveOrUploadImage('server')">上传</el-button>
            <!-- <a id="btnSave" class="btnLoadAndSave" v-on:click="saveOrUploadImage('local')">保存至本地存储 &gt;</a> -->
            <!-- <el-button type="primary" link @click="saveOrUploadImage('local')">保存至本地存储 &gt;</el-button> -->
          </li>
        </ul>
      </div>
      <div id="divUploadedFiles" style="display: none">
        <div id="resultWrap"></div>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
/* stylelint-disable selector-id-pattern */
#divSaveDetail {
  .fileDir {
    margin-top: 4px;
    .el-input {
      margin-top: 4px;
      font-size: 14px;
      .el-input__inner {
        margin: 0;
        border: none;
      }
    }
    .file-dic-line {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .el-icon {
        font-size: 26px;
        color: var(--el-color-primary);
        cursor: pointer;
      }
    }
  }
  .file-name {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    margin-top: 4px;
    .name-content {
      display: flex;
      align-items: flex-end;
    }
    .el-input__inner {
      margin: 0;
      border: none;
    }
    .el-icon {
      font-size: 24px;
      color: var(--el-color-primary);
      cursor: pointer;
    }
  }
  .page-range {
    display: flex;
    align-items: center;
    margin: 6px 0;
    .el-radio-group {
      margin-left: 8px;
      .el-radio {
        display: flex;
        align-items: center;
        height: 20px;
      }
      .el-input {
        width: 81px;
      }
    }
  }
  #txt_CustomInfo {
    border-color: #dcdfe6;
    border-radius: 4px;
  }
  .save-btns {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
